﻿using System;
using System.Collections;
using System.Web.UI;
using Trentacular.SharePoint.Features.Util;

namespace Trentacular.SharePoint.Features.Web.UI.WebControls
{
    public class DelegateDataSourceView : DataSourceView
    {
        public DelegateDataSource Owner { get; private set; }
        public const string DefaultViewName = "Default_View";

        public DelegateDataSourceView(DelegateDataSource owner)
            : base(owner, DefaultViewName)
        {
            Owner = owner;
        }

        public override bool CanDelete { get { return true; } }
        public override bool CanInsert { get { return true; } }
        public override bool CanUpdate { get { return true; } }

        public override bool CanPage { get { return Owner.CanPage; } }
        public override bool CanRetrieveTotalRowCount { get { return Owner.CanRetrieveTotalRowCount; } }
        public override bool CanSort { get { return Owner.CanSort; } }

        protected virtual IEnumerable Sort(IEnumerable results, string sortExpression)
        {
            var sortArgs = sortExpression.Split(' ');
            if (sortArgs.Length == 0)
                return results;

            var sortProperty = sortArgs[0];
            if (sortProperty.Length == 0)
                return results;

            var reverse = false;
            if (sortArgs.Length > 1 && sortArgs[1].Equals("desc", StringComparison.CurrentCultureIgnoreCase))
                reverse = true;

            return results.Sort(reverse, sortProperty);
        }

        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments args)
        {
            var results = Owner.OnSelect(args);

            // Sort the results if AutoSort is specified
            if (Owner.AutoSort)
                return Sort(results, args.SortExpression);

            return results;
        }

        protected override int ExecuteInsert(IDictionary values)
        {
            return Owner.OnInsert(values);
        }

        protected override int ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues)
        {
            return Owner.OnUpdate(keys, values, oldValues);
        }

        protected override int ExecuteDelete(IDictionary keys, IDictionary oldValues)
        {
            return Owner.OnDelete(keys, oldValues);
        }
    }
}
